<template>
  <el-card class="form-container" shadow="never">
    <el-tree :data="menuTreeList" show-checkbox default-expand-all node-key="id" ref="treeRef" highlight-current :props="defaultProps">
    </el-tree>
    <div style="margin-top: 20px">
      <el-button type="primary" @click="handleSave()">保存</el-button>
      <el-button @click="handleClear()">清空</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { fetchTreeList } from '@/api/menu'
import { listMenuByRole, allocMenu } from '@/api/role'
import { ref } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import type { MenuTree } from '@/models/menu'
import type { TreeKey } from 'element-plus/lib/components/tree-v2/src/types.js'

defineOptions({ name: 'AllocMenu' })
const defaultProps = {
  children: 'children',
  label: 'title',
}
const route = useRoute()
const router = useRouter()
const treeRef = ref<InstanceType<typeof ElTree>>()
const menuTreeList = ref<MenuTree[]>([])
const roleId = ref(0)
roleId.value = Number(route.query.roleId)

treeList()
getRoleMenu(roleId.value)

async function treeList() {
  const response = await fetchTreeList()
  menuTreeList.value = response.data.data
}

async function getRoleMenu(roleId: number) {
  const response = await listMenuByRole(roleId)
  const keys: TreeKey[] = response.data.data?.filter((item) => item.parentId !== 0).map((item) => item.id as number) || []
  treeRef.value?.setCheckedKeys(keys)
}

async function handleSave() {
  let checkedNodes = treeRef.value?.getCheckedNodes()
  let checkedMenuIds = new Set()
  checkedNodes?.forEach((item) => {
    checkedMenuIds.add(item.id)
    item.parentId !== 0 && checkedMenuIds.add(item.parentId)
  }) || []
  let params = {
    roleId: roleId.value,
    menuIds: Array.from(checkedMenuIds).join(','),
  }
  await allocMenu(params)
  ElMessage.success('分配成功')
  router.back()
}

function handleClear() {
  treeRef.value?.setCheckedKeys([])
}
</script>

<style scoped></style>
